package com.fbinggun.dt.task;

import com.fbinggun.dt.DailyTask;
import com.fbinggun.dt.player.PlayerData;
import com.fbinggun.dt.task.conditions.Conditions;
import com.fbinggun.fbinggunutil.BukkitUtil;
import com.fbinggun.fbinggunutil.ItemUtil;
import com.fbinggun.fbinggunutil.PApiUtil;
import com.fbinggun.fbinggunutil.TiemUtil;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class Task {
    ConfigurationSection config;
    String permission;
    List<String> reward;
    Long timeLimit;
    Map<String,Conditions> conditionsList;
    String id;
    String msg;

    public Long getTimeLimit() {
        return timeLimit;
    }

    public Task(String id, ConfigurationSection config) {
        this.config = config;
        this.id=id;
        permission=config.getString("Permission");
        reward=config.getStringList("Reward");
        timeLimit=config.getLong("TimeLimit");
        conditionsList= Conditions.newConditions(config.getConfigurationSection("Conditions"),this);
        msg=config.getString("Msg");
        DailyTask.debug("载入任务成功："+id);
    }

    public String getId() {
        return id;
    }

    public Conditions getConditions(String id){
        return conditionsList.get(id);
    }
    public ItemStack getItem(Player player){
        ItemStack itemStack = ItemUtil.getItemStack(config.getConfigurationSection("Item"));
       itemStack= PApiUtil.setPlaceholder(itemStack,player);
        return itemStack;
    }

    //是否完成了任务
    public boolean isFinish(PlayerData playerData){
        if(playerData.getTask()==null){
            return false;
        }
        if(conditionsList==null||conditionsList.size()==0){
            return true;
        }
        for(Conditions conditions:conditionsList.values()){
            if(playerData.getCount(conditions)<conditions.getCount()){
                return false;
            }
        }
        return true;
    }

    public void reward(Player player) throws SQLException, ClassNotFoundException {
        PlayerData playerData = DailyTask.getPlayerData(player);
        if(isFinish(playerData)){
            if(reward!=null) {
                BukkitUtil.runCommands(reward, player, DailyTask.plugin);
            }
            playerData.removeTask();
            player.sendMessage(PApiUtil.setPlaceholders(player,msg));
        }
    }

    public String getTiemLimitString(PlayerData playerData) throws Exception {
        if(playerData.getTask()==null){
            return TiemUtil.stampToTimeMillisecond(timeLimit*1000+TiemUtil.date(),"MM月dd日 HH:mm");
        }
        return playerData.getTask().getTiemLimitString();
    }


}
